/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package gui;

import interfaces.EditPanel;

import java.awt.Dimension;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import database.DBConnectionFactory;

/**
 * Settings panel for buildings
 * 
 * 
 */
public class TextInputPanel extends JPanel implements EditPanel {
   private static final long serialVersionUID = 4228896307757033356L;
   private JTextField name;
   private JTextArea regex;
   private JComboBox type;
   private JTextField accessCommand;
   private JTextField resetCommand;
   private String itemName;
   private final DialogPanel parent;

   public TextInputPanel(final DialogPanel parent) {
	  super();
	  this.parent = parent;
	  initialize();
   }

   @Override
   public void checkInputs() {
	  if (name.getText().equals("") || regex.getText().equals("")) {
		 parent.setSaveButtonEnabled(false);
	  } else {
		 parent.setSaveButtonEnabled(true);
	  }
   }

   @Override
   public boolean delete() {
	  if ("".equals(itemName))
		 return false;
	  PreparedStatement ps = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM textinput WHERE name = ?");
		 ps.setString(1, itemName);
		 ps.executeUpdate();
		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }

   @Override
   public String getItemName() {
	  return itemName;
   }

   /**
    * Initializes the components
    */
   private void initialize() {
	  setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
	  setMinimumSize(new Dimension(360, 400));
	  name = new JTextField();
	  name.setPreferredSize(new Dimension(300, 20));
	  name.getDocument().addDocumentListener(new MyDocumentListener(this));
	  regex = new JTextArea();
	  regex.setRows(4);
	  regex.setLineWrap(true);
	  regex.setPreferredSize(new Dimension(300, 20));
	  regex.getDocument().addDocumentListener(new MyDocumentListener(this));
	  type = new JComboBox(new String[] { "Self Spell", "Duration Spell/Op", "Duration Spell/Op w/o prov name",
			"Instant Damage Spell/Op", "Instant Damage Spell/Op w/o prov name" });
	  type.setPreferredSize(new Dimension(300, 20));
	  accessCommand = new JTextField();
	  accessCommand.setPreferredSize(new Dimension(300, 20));
	  accessCommand.getDocument().addDocumentListener(new MyDocumentListener(this));
	  resetCommand = new JTextField();
	  resetCommand.setPreferredSize(new Dimension(300, 20));
	  resetCommand.getDocument().addDocumentListener(new MyDocumentListener(this));

	  this.add(new CustomPanel(new CustomLabel("Name", 120, 20), name));
	  this.add(new CustomPanel(new CustomLabel("Regex", 120, 20), regex));
	  this.add(new CustomPanel(new CustomLabel("Type", 120, 20), type));
	  this.add(new CustomPanel(new CustomLabel("Access Command", 120, 20), accessCommand));
	  this.add(new CustomPanel(new CustomLabel("Reset Command", 120, 20), resetCommand));
   }

   @Override
   public JPanel load(final String item) {
	  itemName = item;
	  removeAll();
	  validate();
	  initialize();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM textinput WHERE name = ?");
		 ps.setString(1, item);
		 rs = ps.executeQuery();

		 if (rs.next()) {
			name.setText(rs.getString("name"));
			regex.setText(rs.getString("regex"));
			type.setSelectedIndex(rs.getInt("inputtype") - 1);
			accessCommand.setText(rs.getString("accesscommand"));
			resetCommand.setText(rs.getString("resetcommand"));
		 } else {
			name.setText(item);
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return this;
   }

   @Override
   public boolean save() {
	  if (name.getText().equals("") || regex.getText().equals(""))
		 return false;
	  PreparedStatement ps = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM textinput WHERE name = ?");
		 ps.setString(1, itemName);
		 ps.executeUpdate();

		 try {
			ps.close();
		 } catch (final Exception e) {
		 }

		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("INSERT INTO textinput VALUES(?,?,?,?,?)");
		 ps.setString(1, name.getText());
		 ps.setString(2, regex.getText());
		 ps.setInt(3, type.getSelectedIndex() + 1);
		 ps.setString(4, accessCommand.getText());
		 ps.setString(5, resetCommand.getText());
		 ps.executeUpdate();

		 itemName = name.getText();
		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }
}
